package com.longteng.diamond.service;

import com.google.common.base.Splitter;
import com.longteng.diamond.constant.ConstantType;
import com.longteng.diamond.domain.BuildTest;
import com.longteng.diamond.domain.TestPlan;
import com.longteng.diamond.util.FileUtil;
import com.longteng.diamond.util.PicReport;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.jfree.data.general.DefaultPieDataset;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.javamail.JavaMailSender;

import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

import javax.mail.internet.MimeMessage;
import java.io.File;
import java.io.IOException;
import java.io.StringWriter;
import java.util.List;

/**
 * Created by Administrator
 * DATE : 2018/8/25
 * TIME : 19:27
 * PROJECT : java-lesson
 * PACKAGE : com.longteng.lesson
 *
 * @author <a href="mailto:taki@qq.com">Administrator</a>
 */
@Slf4j
@Component
public class MailReportService {
    @Autowired
    JavaMailSender javaMailSender;
    @Autowired
    TestPlanService testPlanService;
    @Value("${spring.mail.from}")
    private String from;
    @Autowired
    FreeMarkerConfigurer freeMarkerConfigurer;

    /**
     * 发送邮件
     *
     * @param buildTest
     * @return requestResult
     */
    public void sendMail(BuildTest buildTest) {

        Integer testPlanId = buildTest.getTestPlanId();
        /**
         * 如果不为空说明执行的是测试计划
         * **/
        if (null != testPlanId) {
            TestPlan testPlan = testPlanService.getTestPlanById(testPlanId);
            String sendTo = testPlan.getSendTo();
            /**
             * 如果收件人地址不为空才发送邮件
             * */
            if (!StringUtils.isBlank(sendTo)) {
                /**
                 * 获取模板的配置
                 * **/
                Configuration configuration = freeMarkerConfigurer.getConfiguration();
                String pngPath = null;
                try {
                    StringWriter writer = new StringWriter();
                    /**
                     * 获取邮件正文的模板
                     * */
                    Template template = configuration.getTemplate("/page/mail/mailPage.ftl");
                    try {
                        /**
                         * 把数据对象扔到模板里面
                         * stringWriter是为了把模板的信息转成字符串
                         * **/
                        template.process(buildTest, writer);
                    } catch (TemplateException e) {
                        log.error("处理模板异常", e);
                    }
                    /**
                     * 定义图片名称
                     * **/
                    pngPath = buildTest.getBuildTestId() + buildTest.getTestPlanId() + "report.png";
                    pic(buildTest, pngPath);
                    send(sendTo, writer.toString(), pngPath);
                } catch (IOException e) {
                    log.error("未找到邮件模板", e);
                } finally {
                    FileUtil.deleteFile(pngPath);
                }
            }
        }

    }

    /**
     * 生成图片
     *
     * @param buildTest
     * @return
     */
    public void pic(BuildTest buildTest, String pngPath) {
        DefaultPieDataset dataset = new DefaultPieDataset();
        String casePassCount = buildTest.getPassCaseSize().toString();
        String caseFailCount = (buildTest.getCaseSize() - buildTest.getPassCaseSize()) + "";
        dataset.setValue("PassCase", new Double(casePassCount));
        dataset.setValue("FailCase", new Double(caseFailCount));
        PicReport picReport = new PicReport();
        picReport.save(dataset, pngPath, "通过率");
    }

    /**
     * 发送邮件
     *
     * @param sendTo
     * @param html
     * @param pngPath
     * @return
     */
    public void send(String sendTo, String html, String pngPath) {
        MimeMessage mimeMailMessage = javaMailSender.createMimeMessage();
        try {
            MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMailMessage, true);
            mimeMessageHelper.setFrom(from);
            if (sendTo.contains(ConstantType.STRSPLIT)) {
                String[] array=sendTo.split(ConstantType.STRSPLIT);
                mimeMessageHelper.setTo(array);
            } else {
                mimeMessageHelper.setTo(sendTo);
            }
            mimeMessageHelper.setSubject("接口测试报告");
            mimeMessageHelper.setText(html, true);
            FileSystemResource file = new FileSystemResource(new File(pngPath));
            mimeMessageHelper.addInline("passRate", file);
            javaMailSender.send(mimeMailMessage);
        } catch (Exception e) {
            log.error("发送邮件异常", e);
        }
    }
}
